﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Comet.Net;
using Comet.Timers;
using System.Globalization;
using System.Net;
using System.Web;
using Comet.Samples.Properties;

namespace Comet.Samples.Time {
    internal class CometTimeHandler : CometBusHandler<DateTime> {

		#region Fields (3) 

        private readonly CultureInfo _culture;
        private readonly string _html;
        private readonly TimeTimer _timer;

		#endregion Fields 

		#region Constructors (1) 

        public CometTimeHandler (TimeZoneInfo timeZone) {
            _culture = CultureInfo.CurrentUICulture;
            _html = Resources.Index.Replace ("@TIMEZONE@", HttpUtility.HtmlEncode (timeZone.DisplayName));
            _timer = new TimeTimer (TimeInterval.Second, delegate {
                Bus.Publish (TimeZoneInfo.ConvertTime (DateTime.Now, timeZone));
            });
            _timer.Start ();
        }

		#endregion Constructors 

		#region Methods (8) 


		// Public Methods (3) 

        public override void HandleRequest (HttpListenerContext httpListenerContext, bool waitHandleTimedOut) {
            DateTime dateTime = Bus.Value;
            HttpListenerResponse response = httpListenerContext.Response;
            response.ContentType = "application/json";
            Send (response, Json (dateTime));
        }

        public string Json (DateTime dateTime) {
            StringBuilder sb = new StringBuilder ();
            sb.Append ("{\r\n");
            sb.Append ("\"date\": \"");
            sb.Append (HttpUtility.HtmlEncode (dateTime.ToString ("D", _culture)));
            sb.Append ("\",\r\n");
            sb.Append ("\"hour\": \"");
            sb.Append (dateTime.ToString ("hh", _culture));
            sb.Append ("\",\r\n");
            sb.Append ("\"minute\": \"");
            sb.Append (dateTime.ToString ("mm", _culture));
            sb.Append ("\",\r\n");
            sb.Append ("\"second\": \"");
            sb.Append (dateTime.ToString ("ss", _culture));
            sb.Append ("\",\r\n");
            sb.Append ("\"tt\": \"");
            sb.Append (HttpUtility.HtmlEncode (dateTime.ToString ("tt", _culture)));
            sb.Append ("\"\r\n");
            sb.Append ("}");
            return sb.ToString ();
        }

        public override bool RequestReceived (HttpListenerContext httpListenerContext, ref long waitHandleTimeout) {
            string url = httpListenerContext.Request.RawUrl;
            if (url.Contains ("current"))
                return true; // this is a comet request
            else { // this is a static request
                HttpListenerResponse response = httpListenerContext.Response;
                if (url.Contains ("jquery"))
                    JQuery (response); // send jquery
                else if (url.Contains ("js"))
                    JS (response);
                else if (url.Contains ("css"))
                    Css (response);
                else if (url.EndsWith ("/"))
                    Default (response); // send html
                else
                    using (response) {
                        response.Redirect (url + "/");
                    }
                return false;
            }
        }



		// Private Methods (5) 

        private void Css (HttpListenerResponse response) {
            response.ContentType = "text/css";
            Send (response, Resources.Css);
        }

        private void Default (HttpListenerResponse response) {
            response.ContentType = "text/html";
            Send (response, _html);
        }

        private void JQuery (HttpListenerResponse response) {
            response.ContentType = "text/javascript";
            Send (response, Resources.JQuery);
        }

        private void JS (HttpListenerResponse response) {
            response.ContentType = "text/javascript";
            Send (response, Resources.JS);
        }

        private static void Send (HttpListenerResponse response, string result) {
            response.Headers.Add ("Expires: Thu, 29 Oct 1998 17:04:19 GMT");
            byte[] content = Encoding.UTF8.GetBytes (result);
            response.ContentLength64 = content.Length;
            try {
                response.Close (content, false);
            }
            catch (HttpListenerException) {
                // ignore
            }
        }


		#endregion Methods 

    }

}
